const express = require('express');
const router = express.Router();

const mail = require('../utils/mail');

router.post('/v1/mail/send', async (req, res) => {
  const { target, title, content } = req.body;
  console.log(target, title, content);
  try {
    const send = await mail(target, title, content);
    console.log(send);
    res.send({
      code: 200,
      data: 'ok'
    })
  } catch (err) {
    if (err.response) {
      res.send({ code: 500, data: err.response.data });
    } else {
      res.send({ code: 500, data: err });
    }
  }
})

router.post('/v1/mail/code', async (req, res) => {
  const { email } = req.body;
  const code = parseInt(Math.random() * 999999);
  const text = `【智汇乡兴】验证码为 ${code} 。若非本人操作，请忽略此邮件。`
  try {
    const send = await mail(email, '邮箱验证码', text);
    res.send({
      code: 200,
      data: {
        code
      }
    })
  } catch (err) {
    if (err.response) {
      res.send({ code: 500, data: err.response.data });
    } else {
      res.send({ code: 500, data: err });
    }
  }
})

module.exports = router;